<template>
  <div class="securityContent" :class="scroll.isFixed ? 'securityContentFixed' : ''"  id="securityContent">
    <!-- 功能按钮 -->
    <div class="securityContent_button">
      <a-button class="addButton" type="primary" 
      :disabled="!btnPerm.includes('creatAble')"
      @click="addRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        新建
      </a-button>
    </div>

    <!-- 表格展示部分 -->
    <baseTable :columns="columns.securityContentColumns" :dataSource="configData.records" :isSelect="true"
      :scroll="scroll" ref="baseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" @deleteRecord="deleteSelectedAll" @changePage="changePage">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('editAble') }" @click="eidtRecord(record)">{{ record.oparation[0] }}</a>
          <a-popconfirm placement="topRight" 
          :disabled="!btnPerm.includes('deleteAble')"
          @confirm="confirmDelete(record)">
            <template #title>
              <p style="width: 197px">
                若有内容绑定过此密级，则会删除失败，在【内容管理】栏目下可以进行筛选密级后批量操作
              </p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">{{ record.oparation[1] }}</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')">删除</a-button>
      </template>
    </baseTable>

    <!-- 新建内容/附件密级模态框 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false" class="securitycontent_modal">
      <template v-slot:body>
        <a-form name="advanced_search" class="ant-advanced-search-form" autoComplete="off" :model="formState"
          ref="contentFrom">
          <a-form-item :name="['securityName', 'value']" :label="formState.securityName.label"
            :rules="[formState.securityName.rule]">
            <a-input v-model:value="formState.securityName.value" show-count :maxlength="25" allow-clear />
          </a-form-item>
          <a-form-item class="tag-item" :name="['securityLevel', 'value']" :label="formState.securityLevel.label"
            :rules="[formState.securityLevel.rule]">
            <a-input-number id="inputNumber" v-model:value="formState.securityLevel.value" :min="1" />
            <p class="model-tip">数字越大意味着密级越高</p>
          </a-form-item>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, reactive, onMounted, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
import { checkSequrity } from "./formRuler";
import {routerPerm} from '@/utils/common';
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}

//props
const props = defineProps({
  secretType: {
    type: Number,
    default: 1,
  },
});

//data
const btnPerm = ref<any[]>([]);
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
let beforeItem: dataSourceType = reactive({ level: 1, name: "" });
//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
const deleteArr = ref<(string | number)[]>([]);
const baseTables = ref<any>(null);
let rowSelection = ref<(string | number)[]>([]);
// 模态框数据
const isAddOrEdit = ref<boolean>(true); //判断是新家、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
const modAlProps: modeProp = reactive({
  width: "M",
  title: "新建密级",
});

let datas = {
  pageNumber: 0,
  pageSize: 10,
};
const contentFrom = ref<any>("contentFrom");

const formState = reactive<dataSourceType>({
  securityName: {
    value: "",
    rule: {
      required: true,
      validator: checkSequrity,
      trigger: ["blur"],
      msg1: "密级名称不能为空！",
      msg2: "密级名称已存在！",
      api: "fetchSecretUnique",
      type: "name",
      secretType: props.secretType,
      params: { id: "" },
    },
    label: "密级名称",
  },
  securityLevel: {
    value: "",
    rule: {
      required: true,
      validator: checkSequrity,
      trigger: ["blur"],
      msg1: "密级等级不能为空！",
      msg2: "密级等级已存在！",
      api: "fetchSecretUnique",
      type: "level",
      secretType: props.secretType,
      params: { id: "" },
    },
    label: "密级等级",
  },
  id: "",
});

const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
//methods
const addRecord = async () => {
  //新加内容/附件密级模态框条件修改
  //添加内容/附件密级数据
  isVisible.value = true;
  isAddOrEdit.value = true;
  modAlProps.title = "新建密级";
  formState.securityName.value = "";
  formState.securityLevel.value = "";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

const eidtRecord = async (item: dataSourceType) => {
  if(!btnPerm.value.includes('editAble')) return
  //编辑内容/附件密级数据
  isAddOrEdit.value = true;
  modAlProps.title = "编辑密级";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  beforeItem = item;
  formState.securityName.value = item.name;
  formState.securityLevel.value = item.level;
  formState.securityName.rule.params.id = item.id;
  formState.securityLevel.rule.params.id = item.id;
  formState.id = item.id;
  isVisible.value = true;
};

const buttonMessage = async (msg: dataSourceType) => {
  // 新添或编辑内容/附件密级调取接口
  //保存
  contentFrom.value
    .validate()
    .then(() => {
      let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";
      const params = new FormData();
      if (type === "Edit") {
        // if()
        params.append("id", formState.id);
        if (beforeItem.name !== formState.securityName.value) {
          params.append("name", formState.securityName.value);
        }
        if (beforeItem.level !== formState.securityLevel.value) {
          params.append("level", formState.securityLevel.value);
        }
        if (
          beforeItem.name === formState.securityName.value &&
          beforeItem.level === formState.securityLevel.value
        ) {
          isVisible.value = false;
          return;
        }
      } else {
        params.append("name", formState.securityName.value);
        params.append("level", formState.securityLevel.value);
        params.append("secretType", props.secretType.toString());
      }
      request[type === "Edit" ? "fetchSecretUpdate" : "fetchSecretAdd"](params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            getRdecord();
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
      isVisible.value = msg.text == "保存" ? false : true;
    })
    .catch(() => { });
};

const confirmDelete = async (item: any) => {
  // 删除单个内容/附件密级
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};

const deleteSelectedAll = async () => {
  //删除已选所有内容/附件密级
  let keys = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "",
      content:
        "是否确认删除，删除后将关联该密级的内容同步解除密级设置",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",
      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};
const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除内容/附件密级
  await request
    .fetchSecretDelete({ ids: keys, secretType: props.secretType })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRdecord();
      } else {
        props.secretType == 2
          ? message.error("附件密集已绑定")
          : message.error("内容密集已绑定");
      }
    });
};

const getRdecord = async () => {
  // 获取表格数据
  const postData: {} = {
    pageNumber: datas.pageNumber || 0,
    pageSize: datas.pageSize || 10,
    secretType: props.secretType,
  };
  const data = (await request.fetchSecretList(postData)) || {};
  let reqData = data;
  let sourceData = ref<dataSourceType[]>([]);
  const records: any[] = [];
  reqData?.records.map((item: any, index: number) => {
    sourceData = {
      ...item.middleDto,
      oparation: ["编辑", "删除"],
      num: index + 1,
      name: item.name,
      level: item.level,
      id: item.id,
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  baseTables.value.selectedRowKeys = [];
  nextTick(() => {
    scroll.y = getTableScroll(74, "securityContent").y;
    scroll.isFixed = getTableScroll(74, "securityContent").isFixed;
  });
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  getRdecord();
};

// computed
rowSelection = computed(() => {
  return baseTables.value.selectedRowKeys;
});
//onmounted
onMounted(() => {
  btnPerm.value = routerPerm()
  getRdecord();
});
</script>
<style lang="scss" scoped>
.securityContent {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;
  overflow: hidden;

  .securityContent_button {
    padding-bottom: 16px;
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .searchContent {
      margin-left: auto;
      margin-right: 0px;
    }
  }


  .eidtRecords {
    margin-right: 16px;
  }
}
.securityContentFixed {
  width: 100%;
  height: calc(100% - 120px);
}
.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}
.model-tip {
  margin-top: 8px;
  margin-left: 4px;
  font-size: 12px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.45);
}

.tag-item {
  margin-bottom: 0 !important;
}


::v-deep(.ant-table-cell:nth-last-of-type(1)) {
  text-align: right;
  margin-right: 16px;
}

::v-deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
}

::v-deep(.ant-input-number) {
  width: 136px;
  margin-left: 4px;
}

::v-deep(.ant-input-affix-wrapper) {
  width: 506px;
  margin-left: 4px;
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}

::v-deep(.anticon-close-circle) {
  display: none;
}
</style>
